package com.zzyl.nursing.dto;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.poi.ss.usermodel.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author gyf
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 查询入住详情信息
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo getCheckInDetailVo(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //1.查询老人信息
        Long ElderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(ElderId);
        //计算老人年龄
        String birthday = elder.getIdCardNo().substring(6, 14);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyMMdd");
        LocalDate birthDate = LocalDate.parse(birthday, dateTimeFormatter);
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 使用Period计算两个日期之间的差值
        Period period = Period.between(birthDate, currentDate);

        //封装老人信息VO
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInElderVo.setAge(period.getYears());

        //2.查询家属信息
        List<ElderFamilyVo> list = (List<ElderFamilyVo>)JSON.parse(checkIn.getRemark());

        //3.查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));

        //封装入住配置VO
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);

        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());


        //4.查询签约办理信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, ElderId));


        //封装入住详情VO
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(list);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);


        return checkInDetailVo;
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //检查老人是否入住
        String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, idCardNo).in(Elder::getStatus, 1, 4));
        if (elder != null) {
            throw new BaseException("老人已入住");
        }

        //更新床位状态为已入住
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = new Bed();
        bed.setId(bedId);
        bedMapper.update(bed, new LambdaUpdateWrapper<Bed>().setSql("bed_status = 1").eq(Bed::getId, bedId));


        //查询床位信息
        bed = bedMapper.selectBedById(bedId);

        //新增或修改老人信息
        elder = insertOrUpdate(checkInApplyDto.getCheckInElderDto(), bed);

        //新增签约办理
        insertContract(checkInApplyDto,elder);

        //新增入住信息
        CheckIn checkin = new CheckIn();
        checkin.setElderName(elder.getName());
        checkin.setElderId(elder.getId());
        checkin.setIdCardNo(elder.getIdCardNo());
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkin);
        checkin.setBedNumber(bed.getBedNumber());
        //封装亲属信息到remark
        checkin.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        //插入入住信息
        insertCheckIn(checkin);


        //新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkin.getId());
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfigMapper.insert(checkInConfig);

    }

    //新增签约办理
    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        //生成合同编号
        String number = CodeGenerator.generateContractNumber();

        //封装数据
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(number);
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contractMapper.insert(contract);
    }

    //新增或修改老人信息
    public Elder insertOrUpdate(CheckInElderDto checkInElderDto,Bed bed) {
        //根据身份证号查找老人信息
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));


        //准备新的老人数据
        Elder newElder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, newElder);
        newElder.setBedNumber(bed.getBedNumber());
        newElder.setBedId(bed.getId());


        if (elder != null) {
            //修改
            newElder.setId(elder.getId());
            elderMapper.updateById(newElder);
        } else {
            //新增
            elderMapper.insert(newElder);
        }

        return newElder;
    }
}
